package com.zzz.demo.controller;

import com.zzz.demo.entity.User;
import com.zzz.demo.service.UserService;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private MongoTemplate mongoTemplate;

    @RequestMapping("/get/{id}")
    public User getUser(@PathVariable int id) {
        return userService.getUser(id);
    }

    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable int id) {
        userService.remove(id);
        return "delete sucess";
    }


    @RequestMapping("/addDoc")
    public String insertDoc() {
        Document document = new Document();
        document.append("id",123)
                .append("name","ZZZ")
                .append("age",26)
                .append("grade",1)
                .append("integral",1000)
                .append("gender","male");
        mongoTemplate.getCollection("test").insertOne(document);
        return "sucess";
    }

    @GetMapping("/addUser")
    public String addUser() {
        for (int i = 0; i < 100; i++) {
            User user = new User();
            user.setAge(new Random().nextInt(30));
            String email = UUID.randomUUID().toString().substring(0, 8);
            user.setEmail(email + "@163.com");
            user.setGender("male");
            mongoTemplate.save(user);
        }
        return "success";
    }

    @GetMapping("/listUser")
    public List<User> listUser() {
        List<User> userList = mongoTemplate.findAll(User.class);
        return userList;
    }


    @RequestMapping("/find/all")
    public List<User> find() {
        return userService.findAll();
    }

    @RequestMapping("/find/{start}")
    public List<User> findByPage(@PathVariable int start, User user) {
        Pageable pageable = new PageRequest(start, 2);
        return userService.findByPage(user, pageable);
    }

}